<template>
  <div>
    <page-layout>
      <a-row :gutter="[10, 10]">
        <a-col :span="24">
          <a-card>
            <a-form
              ref="formRef"
              :rules="formRules"
              :model="modelForm.data"
              :label-col="{ span: 5 }"
              :wrapperCol="{ span: 15 }"
            >
              <a-row>
                <a-col :span="8">
                  <a-form-item
                    :label="t('course-code.label.school')"
                    ref="schId"
                    name="schId"
                  >
                    <a-input v-model:value="modelForm.data.schId">
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('universityVisible')"
                        >
                          选择
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('course-code.label.subjectCategory')">
                    <a-tree-select
                      v-model:value="modelForm.data.disciplineId"
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '360px', overflow: 'auto' }"
                      :tree-data="formState.subjectList"
                      placeholder="学科类别"
                      replace
                      tree-default-expand-all
                      :replaceFields="replaceFields"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('course-code.label.courseCode')">
                    <a-input
                      v-model:value="modelForm.data.courseCode"
                      :maxlength="50"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('course-code.label.courseName')">
                    <a-input
                      v-model:value="modelForm.data.courseName"
                      :maxlength="50"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item>
                    <div style="margin-left: 25px">
                      <a-button
                        type="primary"
                        :disabled="
                          modelForm.data.preCurriculumRelationshipList.length >= 2
                        "
                        @click="handleCourse"
                        >{{
                          t("course-code.title.newModificationHe")
                        }}</a-button
                      >
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-row
                    v-for="(
                      item, index
                    ) in modelForm.data.preCurriculumRelationshipList"
                    :key="index"
                  >
                    <a-col :span="8">
                      <a-form-item :label="t('course-code.label.preCourse')">
                        <a-input v-model:value="item.courseCodeId">
                          <template #addonAfter>
                            <div
                              class="primary-color cursor-pointer"
                              @click="openDialog('visiableCourse', index)"
                            >
                              选择
                            </div>
                          </template>
                        </a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :span="8">
                      <a-form-item
                        :label="t('course-code.label.preCourseRelationship')"
                      >
                        <a-select v-model:value="item.relationship">
                          <a-select-option
                            v-for="(item, index) in dictLists.data[
                              dictEnum.COURSE_RELATION
                            ]"
                            :key="index"
                            :value="item.value"
                          >
                            {{ item.label }}
                          </a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :span="8">
                      <a-button
                        style="margin-left: 20px"
                        type="danger"
                        @click="handleDel(item, index)"
                        >{{ t("button.delete") }}</a-button
                      >
                    </a-col>
                  </a-row>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
      <school
        :visible="formState.universityVisible"
        @close="closeDialog"
        @submitSchool="selectUniversity"
      />
      <course
        :visible="formState.visiableCourse"
        @close="closeDialog"
        @submitCourse="selectCourse"
      />
    </page-layout>
    <footer-button :buttons="buttons"></footer-button>
  </div>
</template>

<script>
import { defineComponent, reactive, toRaw, onMounted, ref, onDeactivated, onActivated } from "vue";

import {
  save,
  update,
  details,
  coursePage,
  tree,
  dictionary,
} from "@/api/module/course-code-manage";

import school from "./school.vue";
import course from "./course.vue";
import { message, Form } from "ant-design-vue";

import { useI18n } from "vue-i18n";
import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { useRouter, useRoute } from "vue-router";
const useForm = Form.useForm;
export default defineComponent({
  components: {
    school,
    course
  },
  name: "add",
  setup() {
    const { t } = useI18n();
    const router = useRouter()
    const route = useRoute()
    const formRef = ref()
    const formState = reactive({
      universityVisible: false,
      visiableCourse: false,
      subjectList: [],
      courseList: [],
      preCourseList: [],
      itemIndex: 0
    });

    let dictLists = reactive({
      data: {},
    });

    const formRules = reactive({})

    let modelForm = reactive({
      data: {
        courseName: "",
        disciplineId: '',
        schId: '',
        preCurriculumRelationshipList: [],
      }
    });
    const { resetFields, validateInfos } = useForm(
      modelForm.data,
      formRules,
      { deep: true }
    );
    const buttons = [
      {
        name: "save",
        type: "primary",
        code: "",
        event: () => {
          handleSave();
        },
      },
      {
        name: "reset",
        code: "",
        event: () => {
          handleReset();
        },
      },
    ];
    const handleSave = () => {
      const result = toRaw(modelForm.data);
      if (result.id) {
        update(result)
          .then((res) => {
            if (res.success) {
              message.success({ content: "修改成功", duration: 1 });
              router.push({
                path: '/university/course-code-manage'
              })
              formRef.value.resetFields()
            } else {
              message.warning({ content: "修改失败", duration: 1 });
            }
          })
          .catch((err) => {
            message.warning({ content: "修改失败", duration: 1 });
            console.log("err: ", err);
          });
      } else {
        save(result)
          .then((res) => {
            if (res.success) {
              message.success({ content: "保存成功", duration: 1 });
              router.push({
                path: '/university/course-code-manage'
              })
              formRef.value.resetFields()
            } else {
              message.warning({ content: "保存失败", duration: 1 });
            }
          })
          .catch((err) => {
            message.warning({ content: "保存失败", duration: 1 });
            console.log("err: ", err);
          });
      }
    };

    const openDialog = (value, index) => {
      if (index==0||index) {
        formState.itemIndex = index
      }
      formState[value] = true;
    };

    const closeDialog = (value) => {
      formState[value] = false;
    };

    const selectUniversity = (value) => {
      formState["universityVisible"] = false;
      if (value) {
        modelForm.data.schId = value.id;
        modelForm.data.schName = value.schoolCnName;
      }
    };
    const selectCourse = (value) => {
      formState["visiableCourse"] = false;
      if (value) {
        modelForm.data.preCurriculumRelationshipList.map((item, index) => {
          if (formState.itemIndex == index) {
            item.courseCodeId = value.id
          }
          return item
        })
      }
    };

    const getDetails = () => {
      const id = route.query.id||'';
      if (!id) return;
      return details({ id })
        .then((result) => {
          if (result.success) {
            modelForm.data = reactive({
              ...modelForm.data,
              ...result.data
            });
          }
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    };

    getDetails();

    const getSubjectPage = () => {
      return tree()
        .then((result) => {
          if (result.success) {
            formState.subjectList = result.data;
          }
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    };
    const getCoursePage = () => {
      return coursePage({ pageNum: 1, pageSize: 10000 })
        .then((result) => {
          if (result.success) {
            formState.courseList = [...result.data.record];
          }
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    };

    const handleCourse = () => {
      modelForm.data.preCurriculumRelationshipList.push({
        courseCodeId: null,
        relationship: null,
      });
    };

    const handleDel = (row, idx) => {
      modelForm.data.preCurriculumRelationshipList =
        modelForm.data.preCurriculumRelationshipList.filter(
          (item, index) => index != idx
        );
    };

    const getDctionary = () => {
      return dictionary({}).then((res) => {
        if (res.success) {
          formState.preCourseList = res.data;
        }
      });
    };

    const handleReset = () => {
      formRef.value.resetFields()
    };

    getSubjectPage();
    getCoursePage();
    getDctionary();

    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.COURSE_RELATION,
      ]);
    });

    onDeactivated(() => {
      console.log('onDeactivated');
    })
    onActivated(() => {
      console.log('onActivated');
    })

    return {
      t,
      formState,
      modelForm,
      handleSave,
      openDialog,
      closeDialog,
      handleCourse,
      handleDel,
      selectUniversity,
      selectCourse,
      buttons,
      resetFields,
      formRules,

      replaceFields: {
        children: "child",
        title: "disciplineName",
        key: "id",
        value: "id",
      },
      dictLists,
      dictEnum,
      formRef,
    };
  },
});
</script>

<style lang="less" scoped>
.checkeds {
  position: absolute;
  z-index: 9;
  right: 0;
  top: 0;
}
</style>
